<!-- 面诊任务 -->
<template>
  <div>
    <el-row type="flex" justify="space-between" class="mt10">
      <el-col>
        <el-form ref="searchFormRef" :model="searchForm" label-width="80px" :inline="true">
          <el-form-item>
            <el-input v-model="searchForm.customerName" placeholder="姓名、手机号、编号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchBtn">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <!-- <el-col :span="2">
        <el-button @click="addSubscribeBtn">+增加预约</el-button>
      </el-col> -->
    </el-row>
    <el-row class="mt10" type="flex">
      <Search :data="selections" :attribute="'createdTime'" @dateChange="handleDateChange" @change="handleTypeChange" />
      <!-- <el-form :model="searchForm" label-width="80px" :inline="true">
        <el-select v-model="searchForm.warehouseId" placeholder="不限项目类型" clearable>
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-select v-model="searchForm.type" placeholder="不限预约来源" clearable>
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form> -->
    </el-row>
    <el-row class="mt10">
      <TypeSelection :data="filtrateList" :default-value="searchForm.appointmentStatus" :on-change="handleConditionChange" />
    </el-row>
    <!-- 表单区域 -->
    <el-table v-loading="loading" :data="appointmentList">
      <el-table-column label="顺序" type="index" />
      <el-table-column label="顾客" prop="customerName" align="center" />
      <el-table-column label="分诊类型" prop="customerSex" align="center" />
      <el-table-column label="项目分类/项目" prop="projectType" />
      <el-table-column label="排台方式" prop="projectNo" align="center" />
      <el-table-column label="咨询师" prop="projectName" />
      <el-table-column label="主治医师" prop="projectName" />
      <el-table-column label="发起时间" prop="appointmentTime" align="center" min-width="120" />
      <!-- <template slot-scope="scope">
          <span>{{ scope.row.appointmentDate }}</span>&nbsp;
          <span>{{ scope.row.appointmentTime }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="分诊人" prop="receiverName" align="center" />
      <el-table-column label="已等时间" prop="remainingTime" align="center" />
      <el-table-column label="操作" min-width="120" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="signInBtn(scope.row)">开始面诊</el-button>
          <el-button type="text" @click="cancelBtn(scope.row)">结束</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page-num="params.page" :page-size="params.pageSize" :on-change="handlePaginationChange" :total="total" />
    <!-- 添加预约 -->
    <Dialog :title="title" :visible.sync="visible" :button-text="testBtn" :loading="loading" @close="handleClose" @confirm="submitForm">
      <el-form v-show="!flag" ref="subscribeFormRef" :model="subscribeForm" :rules="subscribeFormRules" label-width="100px">
        <el-form-item label="顾客：" prop="customerName">
          <el-autocomplete v-model="subscribeForm.customerName" :fetch-suggestions="querySearch" placeholder="姓名、手机号、编号" @select="handleSelect" />
        </el-form-item>
        <el-form-item label="项目：" prop="projectName">
          <el-select v-model="subscribeForm.projectName" value-key="id" @change="handleSelectProject">
            <el-option v-for="item in projectNameOptions" :key="item.id" :label="item.projectName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="接待人：" prop="receiverName">
          <el-select v-model="subscribeForm.receiverName" value-key="id">
            <el-option v-for="item in receiverOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间：" prop="appointmentDate">
          <el-col :span="6">
            <el-form-item prop="appointmentDate" class="dateStyle">
              <el-date-picker v-model="subscribeForm.appointmentDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期" @change="handleDate" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="appointmentTime" class="dateStyle">
              <el-select v-model="subscribeForm.appointmentTime" placeholder="请选择时段" clearable>
                <el-option v-for="item in cities" :key="item.value" :label="item.value" :value="item.value" :disabled="item.label==='不可预约'?true:false">
                  <span style="float: left">{{ item.value }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="预约备注：" prop="appointmentRemark">
          <el-input v-model="subscribeForm.appointmentRemark" type="textarea" :autosize="{ minRows: 3}" />
        </el-form-item>
      </el-form>
      <el-form v-show="flag" ref="lookSubscribeRef" :model="lookSubscribeForm" :rules="lookSubscribeRules" label-width="150px">
        <el-form-item label="顾客：">{{ lookSubscribeForm.customerName }}</el-form-item>
        <el-form-item label="预约类型：">{{ lookSubscribeForm.appointmentType }}</el-form-item>
        <el-form-item label="接待人：">{{ lookSubscribeForm.receiverName }}</el-form-item>
        <el-form-item label="预约时间：">{{ lookSubscribeForm.appointmentDate }} {{ lookSubscribeForm.appointmentTime }}</el-form-item>
        <el-form-item v-if="searchForm.appointmentStatus!=='已取消'" label="项目分类：">{{ lookSubscribeForm.advisoryClassification }}</el-form-item>
        <el-form-item v-if="title !== '取消预约'" label="预约备注：">{{ lookSubscribeForm.appointmentRemark }}</el-form-item>
        <el-form-item v-if="title !== '预约签到'&&title !== '取消预约'" label="预约状态：">{{ lookSubscribeForm.appointmentStatus }} {{ lookSubscribeForm.arrivalTime?(lookSubscribeForm.arrivalTime):'' }}
        </el-form-item>
        <!-- searchForm.appointmentStatus -->
        <el-form-item v-if="searchForm.appointmentStatus==='已取消'" label="取消原因：">{{ lookSubscribeForm.cancelReason }}</el-form-item>
        <el-form-item v-if="searchForm.appointmentStatus==='已取消'" label="取消备注：">{{ lookSubscribeForm.cancelRemark }}</el-form-item>
        <el-form-item v-if="title === '取消预约'" label="取消原因：" :prop="title === '取消预约'?'cancelReason':''">
          <dictionary-selector code="RESERVE_CANCAL_CODE" :value.sync="lookSubscribeForm.cancelReason" placeholder="取消原因" />
        </el-form-item>
        <el-form-item v-if="title === '取消预约'" label="取消备注：" prop="cancelRemark">
          <el-input v-model="lookSubscribeForm.cancelRemark" type="textarea" :autosize="{ minRows: 3}" />
        </el-form-item>
      </el-form>
    </Dialog>
    <!-- <Add-triage v-if="show" ref="addTriageRef" :visible.sync="show" :show.sync="show" :title="title" /> -->
  </div>
</template>
<script>
// import { DictionarySelector } from "@rabbit.do/rabbit";
import { TypeSelection } from "@monkey.do/monkey";
import Search from "@/components/Search";
// import { selections } from "@/config";
import Dialog from "@/components/Dialog/index";
// import AddTriage from "../triage/dialog";
export default {
  components: {
    TypeSelection,
    // DictionarySelector,
    Search,
    Dialog,
    // AddTriage,
  },
  data() {
    return {
      selections: [{
        name: '前七天',
        id: 'week',
      },
      {
        name: '今天',
        id: 'today',
      },
      {
        name: '昨天',
        id: 'yesterday',
      },
      {
        name: '自定义',
        id: 'custom',
      },
      ],
      filtrateList: [
        {
          name: '全部',
          id: '全部',
        },
        {
          name: '未接待',
          id: '未接待',
        },
        {
          name: '已接待',
          id: '已接待',
        },
        {
          name: '已取消',
          id: '已取消',
        },
      ],
      searchForm: {
        appointmentStatus: '未接待',
      },
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      options: [],
      appointmentList: [{ customerName: '村花' }],
      subscribeForm: {},
      lookSubscribeForm: {},
      projectNameOptions: [],
      receiverOptions: [],
      seleteDate: '', // 预约选择日期
      cities: [], // 预约时段
      selectCustomer: {},
      selectProject: {},
      title: "",
      visible: false,
      testBtn: "",
      loading: false,
      flag: false,
      show: false,
      subscribeFormRules: {
        customerName: [
          { required: true, message: '请输入顾客名称', trigger: ['blur', 'change'] },
        ],
        intentCaseName: [
          { required: true, message: '请选择项目', trigger: 'change' },
        ],
        appointmentDate: [
          { required: true, message: '请选择预约时间', trigger: 'change' },
        ],
      },
      lookSubscribeRules: {
        cancelReason: [
          { required: true, message: '请选择取消原因', trigger: 'change' },
        ],
      },
    };
  },
  mounted() {
    this.getChargeList();
    this.timer = setInterval(() => {
      this.getChargeList();
    }, 1000 * 60);
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    async getChargeList() {
      this.searchForm.deptId = this.$store.getters.currentUserInfo.deptUsrList[0].deptId;
      if (!this.searchForm.deptId) {
        this.searchForm.deptId = 0;
      }
      this.loading = true;
      const res = await this.$api['reception/subscribe/appointmentlist']({ ...this.params, query: this.searchForm });
      this.loading = false;
      if (res.code !== 200) return this.$message.error('查询预约列表失败');
      this.appointmentList = res.data.result;
      this.total = res.data.total;
    },
    handlePaginationChange(val) {
      this.params = { page: val.pageNum, pageSize: val.pageSize };
      this.getChargeList();
    },
    // 搜索
    searchBtn() {
      this.getChargeList();
    },
    // 添加预约
    addSubscribeBtn() {
      this.title = "添加预约";
      this.testBtn = '提交';
      this.visible = true;
      this.flag = false;
      this.loadAll();
      this.getAllByJobName();
    },
    // 签到
    async signInBtn(row) {
      this.title = "预约签到";
      this.testBtn = "签到并分诊";
      this.lookSubscribeForm = row;
      this.flag = true;
      this.visible = true;
    },
    // 取消预约
    cancelBtn(row) {
      this.title = "取消预约";
      this.testBtn = "提交";
      this.lookSubscribeForm = row;
      this.flag = true;
      this.visible = true;
    },

    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item, '顾客');
      this.selectCustomer = { customerId: item.id, appointmentSource: item.informationSources, customerSex: item.sex };
      Object.assign(this.subscribeForm, this.selectCustomer);
      if (item.id) {
        this.getProjectName(item.id);
      }
    },
    handleSelectProject(item) {
      this.selectProject = { projectId: item.projectId, projectName: item.projectName };
      Object.assign(this.subscribeForm, this.selectProject);
    },
    async loadAll() {
      const res = await this.$api['reception/subscribe/findall']();
      if (res.code === 200) {
        res.data.map(item => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    // 顾客已购项目
    async getProjectName(id) {
      const res = await this.$api['reception/subscribe/customerIdAllByOrderList']({ customerId: id });
      console.log(res, '已购项目');
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    async getAllByJobName() {
      const receiverData = await this.$api['reception/subscribe/getAllByJobName']({ hospitalJobName: '咨询师' });
      if (receiverData.code === 200) {
        this.receiverOptions = receiverData.data;
      }
    },
    async getUpdateReportData() {
      const res = await this.$api['reception/subscribe/updateReport']({ ...this.lookSubscribeForm });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.visible = false;
      this.getChargeList();
    },
    submitForm() {
      if (this.title === "添加预约") {
        this.$refs.subscribeFormRef.validate(async valid => {
          if (valid && this.subscribeForm.appointmentTime && this.subscribeForm.appointmentDate) {
            this.subscribeForm.deptName = this.$store.getters.currentUserInfo.deptUsrList[0].deptName;
            this.subscribeForm.deptId = this.searchForm.deptId;
            this.subscribeForm.treatType = "治疗/复查";
            this.loading = true;
            const res = await this.$api['reception/subscribe/addappointment']({ ...this.subscribeForm });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('新增预约失败！');
            this.$message.success('新增预约成功！');
            this.visible = false;
            this.getChargeList();
            this.$refs.subscribeFormRef.resetFields();
          } else {
            this.$message.info('必须选择预约时间！');
          }
        });
      } else if (this.title === "预约签到") {
        this.getUpdateReportData();
        this.$message.success('预约签到成功！');
        this.show = true;
        this.$nextTick(() => {
          this.$refs.addTriageRef.addTriage(this.subscribeForm);
          this.title = "添加分诊";
        });
      } else if (this.title === "取消预约") {
        this.$nextTick(() => {
          this.$refs.lookSubscribeRef.validate(valid => {
            if (valid && this.lookSubscribeForm.cancelReason) {
              this.getUpdateReportData();
              this.$message.success('取消预约成功！');
            } else {
              this.$message.info('请填写取消原因！');
            }
          });
        });
      }
    },
    // 关闭
    handleClose() {
      if (this.title === "添加预约") {
        this.$refs.subscribeFormRef.resetFields();
      } else {
        this.$refs.lookSubscribeRef.resetFields();
      }
    },
    async handleDate() {
      function p(s) {
        return s < 10 ? '0' + s : s;
      }
      const myDate = new Date();
      const year = myDate.getFullYear();
      const month = myDate.getMonth() + 1;
      const day = myDate.getDate();
      const hours = myDate.getHours();
      const minutes = myDate.getMinutes();
      const dates = year + '-' + p(month) + '-' + p(day) + '-' + p(hours) + '-' + p(minutes);
      const currentDate = dates.split('-').join('');
      if (this.subscribeForm.appointmentDate) {
        // 预约时段列表
        const timeData = await this.$api['reception/subscribe/getCreateList']({ dictionaryId: "785558903319429120" });
        if (timeData.code !== 200) return this.$message.error(timeData.message);
        timeData.data.map(item => {
          item.value = item.name + '-' + item.content;
          const aTime = this.subscribeForm.appointmentDate + '-' + item.content;
          const bTime = aTime.split(':').join('');
          this.seleteDate = bTime.split('-').join('');
          // console.log(currentDate, '当前本地时间');
          // console.log(this.seleteDate, '选择预约时间');
          if (Number(currentDate) > Number(this.seleteDate)) {
            item.label = '不可预约';
          } else {
            item.label = '可预约';
          }
        });
        this.cities = timeData.data;
      }
    },
    // 顶部时间筛选
    handleDateChange(val) {
      Object.assign(this.searchForm, val);
      this.getChargeList();
    },
    handleTypeChange(val) {
      Object.assign(this.searchForm, val);
      this.getChargeList();
    },
    handleConditionChange(val) {
      if (val.id === '全部') {
        val.id = '';
      }
      this.searchForm.appointmentStatus = val.id;
      this.getChargeList();
    },
  },
};
</script>
<style lang="scss" scoped>
.dateStyle{
  margin-bottom: 0;
}
::v-deep .el-autocomplete{
  width: 100%;
}
</style>

